package com.visikard.utility;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeoutException;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.visikard.application.Constant;
import com.visikard.application.VKRegApplication;
import com.visikard.system.Theme;
import com.visikard.system.VKregisterConnects;
import com.visikard.ui.R;
import com.visikard.widget.AnimationRelativeLayout;

public class Utils {
	private static final String TAG = null;
	public static boolean bLogin = false;
	public static Dialog uDialog = null;

	public static java.text.DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());

	public static String getConnectValueFromURL(String http) throws Exception {
		String result = "";
		if (http != null) {
			HttpClient client = HttpsUtils.getInstance().sslClient(new DefaultHttpClient());
			HttpGet httpGet = new HttpGet(http);
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, Constant.DEFAULT_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, Constant.DEFAULT_TIMEOUT);
			httpGet.setParams(httpParams);

			HttpResponse response = client.execute(httpGet);
			result = EntityUtils.toString(response.getEntity()).trim();

			client.getConnectionManager().shutdown();
		}

		return result;
	}

	public static void showToast(Context context, String string) {
		Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
	}

	public static void showToast(Context context, int stringId) {
		showToast(context, context.getResources().getString(stringId));
	}

	public static void showToast(Context context, String message, int duration) {
		Toast.makeText(context, message, duration).show();
	}

	public static String getConnectValueFromURLReturnTimeout(String http, int timetout) {
		String result = "";

		if (http != null) {
			HttpClient client = HttpsUtils.getInstance().sslClient(new DefaultHttpClient());
			HttpGet httpGet = new HttpGet(http);
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, timetout);
			HttpConnectionParams.setSoTimeout(httpParams, timetout);
			httpGet.setParams(httpParams);
			try {
				HttpResponse response = client.execute(httpGet);
				result = EntityUtils.toString(response.getEntity()).trim();
			}
			catch (Exception e) {
				if (e instanceof TimeoutException) {
					// Timeout --> nÃªn Ä‘Æ°a vÃ o chuá»‘i káº¿t quáº£
					result = "timeout";
				}
				Log.e("Visikard", "Request exception " + e.getMessage());
			}
			finally {
				client.getConnectionManager().shutdown();
			}
		}

		return result;
	}

	public static void overrideFonts(final View v) {
		try {
			if (v instanceof ViewGroup) {
				ViewGroup vg = (ViewGroup) v;
				for (int i = 0; i < vg.getChildCount(); i++) {
					View child = vg.getChildAt(i);
					overrideFonts(child);
				}
			}
			else if (v instanceof TextView) {
				((TextView) v).setTypeface(Theme.getFontBold());
			}
		}
		catch (Exception e) {
		}
	}

	public static void overrideFonts(View view, String fontName) {
		try {
			if (view instanceof ViewGroup) {
				ViewGroup vg = (ViewGroup) view;
				for (int i = 0; i < vg.getChildCount(); i++) {
					View child = vg.getChildAt(i);
					overrideFonts(child, fontName);
				}
			}
			else if (view instanceof TextView) {
				((TextView) view)
						.setTypeface(Typeface.createFromAsset(VKRegApplication.instance.getAssets(), fontName));
			}
			else if (view instanceof EditText) {
				((EditText) view)
						.setTypeface(Typeface.createFromAsset(VKRegApplication.instance.getAssets(), fontName));
			}
		}
		catch (Exception e) {
		}
	}

	public static void overrideFonts(View view, String fontName, String fontBoldName) {
		try {
			if (view instanceof ViewGroup) {
				ViewGroup vg = (ViewGroup) view;
				for (int i = 0; i < vg.getChildCount(); i++) {
					View child = vg.getChildAt(i);
					overrideFonts(child, fontName, fontBoldName);
				}
			}
			else if (view instanceof TextView) {
				if (((TextView) view).getTypeface().isBold())
					((TextView) view).setTypeface(Typeface.createFromAsset(VKRegApplication.instance.getAssets(),
							fontBoldName));
				else
					((TextView) view).setTypeface(Typeface.createFromAsset(VKRegApplication.instance.getAssets(),
							fontName));
			}
			else if (view instanceof EditText) {
				if (((EditText) view).getTypeface().isBold())
					((EditText) view).setTypeface(Typeface.createFromAsset(VKRegApplication.instance.getAssets(),
							fontBoldName));
				else
					((EditText) view).setTypeface(Typeface.createFromAsset(VKRegApplication.instance.getAssets(),
							fontName));
			}
		}
		catch (Exception e) {
		}
	}

	public static String formatMessageDateTime(Context context, String srcDate) {
		String result = "";
		DateFormat formatter = new SimpleDateFormat(Constant.TIME_FORMAT_STR);
		DateFormat df = new SimpleDateFormat(Constant.TIME_FORMAT_STR_MESSAGE);

		try {
			Date date = formatter.parse(srcDate);
			Date now = new Date();
			result = df.format(date);
			// Add Today to string
			if (!result.equals("") && date.getTime() / Constant.DAY == now.getTime() / Constant.DAY) {
				result = context.getString(R.string.today) + ", " + result;
			}

		}
		catch (Exception e) {

		}

		return result;
	}

	public static String getConnectValueFromHTTPSURL(String http) {
		return getConnectValueFromAllURL(http, true);
	}

	/**
	 * @deprecated
	 * 	Please use getConnectValueFromAllURLWithConnectionState instead
	*/
	public static String getConnectValueFromAllURL(String http, boolean isHttps) {
		String result = "";
		if (http != null) {
			HttpClient client = null;
			if (isHttps) {
				client = HttpsUtils.getInstance().sslClient(new DefaultHttpClient());
			}
			else {
				client = new DefaultHttpClient();
			}
			HttpGet httpGet = new HttpGet(http);
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, Constant.DEFAULT_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, Constant.DEFAULT_TIMEOUT);
			httpGet.setParams(httpParams);
			try {
				HttpResponse response = client.execute(httpGet);
				result = EntityUtils.toString(response.getEntity()).trim();

			}
			catch (IOException e) {
				Log.e("Visikard", "Request exception " + e.getMessage());
				//
			}
			finally {
				client.getConnectionManager().shutdown();
			}
		}
		return result;
	}

	/**
	 * 	NghiDo
	 * */
	public static boolean hasNetworkConnection(Context context) {
		if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
			return false;
		}

		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
		return netInfo != null && netInfo.isConnected();
	}

	public static String format_MM_DD_YYYY(long milisecond) {
		DateFormat df = new SimpleDateFormat(Constant.TIME_FORMAT_STR_US_DATE);
		return df.format(new Date(milisecond));
	}

	public static String getPostConnectValueFromURL(String apiCall, List<NameValuePair> params) throws Exception {
		String result = "";
		String http = VKregisterConnects.getApiContextPathHttp() + apiCall;

		if (http != null) {
			HttpClient client = HttpsUtils.getInstance().sslClient(new DefaultHttpClient());
			HttpPost httpPost = new HttpPost(http);

			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse response = client.execute(httpPost);
			result = EntityUtils.toString(response.getEntity()).trim();
			Log.d("xxx", "API:  " + http);
			Log.d("xxx", "RESPONSE:  " + result);
			Log.d("xxx", "--------------------------------");

			client.getConnectionManager().shutdown();
		}
		return result;
	}

	public static String getPostConnectValueFromHttpsURL(String apiCall, List<NameValuePair> params) {
		String result = "";
		String http = VKregisterConnects.getApiContextPathHttps() + apiCall;
		if (http != null) {
			HttpClient client = HttpsUtils.getInstance().sslClient(new DefaultHttpClient());
			HttpPost httpPost = new HttpPost(http);
			try {
				httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
				httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				HttpResponse response = client.execute(httpPost);
				result = EntityUtils.toString(response.getEntity()).trim();
				Log.d("xxx", "API:  " + http);
				Log.d("xxx", "RESPONSE:  " + result);
				Log.d("xxx", "--------------------------------");
			}
			catch (IOException e) {
				Log.e("Visikard", "Request exception " + e.getMessage());
			}
			finally {
				client.getConnectionManager().shutdown();
			}
		}
		return result;
	}

	public static String getPostConnectValueFromURL(Context context, String apiCall, List<NameValuePair> params)
			throws VKNetworkException {
		String result = "";

		if (!Utils.hasNetworkConnection(context))
			throw new VKNetworkException(VKNetworkException.CODE_NETWORK_DISABLE, "Network not enabled.");
		// Check expire time login
		// if(System.currentTimeMillis() - MyApplication.instance.getLastTimeCallVSKapi() >=
		// Constant.TIME_EXPIRE_LOGIN){
		// loginRefreshSession();
		// }

		String http = VKregisterConnects.getApiContextPathHttp() + apiCall;
		if (http != null) {
			HttpClient client = HttpsUtils.getInstance().sslClient(new DefaultHttpClient());
			HttpPost httpPost = new HttpPost(http);

			try {
				httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
				httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				HttpResponse response = client.execute(httpPost);
				result = EntityUtils.toString(response.getEntity()).trim();
				Log.d("xxx", "API:  " + http);
				Log.d("xxx", "RESPONSE:  " + result);
				Log.d("xxx", "");
				// MyApplication.instance.setLastTImeCallVSKapi(System.currentTimeMillis());
			}
			catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				throw new VKNetworkException(VKNetworkException.CODE_UNSUPPORTED_ENCODING, "Network not enabled.");
			}
			catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				throw new VKNetworkException(VKNetworkException.CODE_PROTOCOL_ERROR, "Network not enabled.");
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				throw new VKNetworkException(VKNetworkException.CODE_UNKNOWN_ERROR, "Network not enabled.");
			}
			finally {
				client.getConnectionManager().shutdown();
			}
		}
		return result;
	}

	public static boolean hasHoneycomb() {
		return Build.VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB;
	}

	public static String ordinal(int i) {
		String[] sufixes = new String[] { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
		switch (i % 100) {
			case 11:
			case 12:
			case 13:
				return i + "th";
			default:
				return i + sufixes[i % 10];

		}
	}

	public static boolean isValidJsonArray(String jarray) {
		return jarray.startsWith("[") && jarray.endsWith("]");
	}

	public static boolean isValidJsonObject(String jarray) {
		return jarray.startsWith("{") && jarray.endsWith("}");
	}

	public final static boolean isValidEmail(String email) {
		if (email == null) {
			return false;
		}
		else {
			return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
		}
	}

	// Return the timezone string like +0700, -0700...
	public final static String getTimeZoneString() {
		TimeZone currentTimeZone = TimeZone.getDefault();
		double zoneOffset = currentTimeZone.getRawOffset() / 3600000;
		String builtZone = "";
		if (zoneOffset < 0) {
			builtZone = "-";
		}
		else {
			builtZone = "+";
		}
		// hour
		builtZone += String.format("%02d", (int) Math.abs(zoneOffset));
		// minute
		builtZone += ":" + String.format("%02d", ((int) (Math.abs(zoneOffset) - Math.abs((int) zoneOffset)) * 60));
		return builtZone;
	}

	public static int compareDateOnly(Date date1, Date date2) {
		long oneDayInMilli = 24 * 3600 * 1000;
		int numberDay1 = (int) (date1.getTime() / oneDayInMilli);
		int numberDay2 = (int) (date2.getTime() / oneDayInMilli);
		if (numberDay1 > numberDay2)
			return 1;
		if (numberDay1 < numberDay2)
			return -1;
		return 0;
	}

	/**
	 * Son direct fragment
	 */
	public static void toFragmentWithoutBackstack(FragmentActivity fragmentActivity, Fragment fragment,
			String tagFragmentNew, int framelayout) {
		try {
			final FragmentManager fm = fragmentActivity.getSupportFragmentManager();
			final FragmentTransaction ft = fm.beginTransaction();
			Fragment existFragment = fm.findFragmentByTag(tagFragmentNew);
			if (existFragment == null) {
				ft.replace(framelayout, fragment, tagFragmentNew);
				ft.addToBackStack(tagFragmentNew);
			}
			else {
				ft.replace(framelayout, existFragment);
			}
			ft.commit();

		}
		catch (Exception exp) {

		}

	}

	public static void toFragment(FragmentManager fm, Fragment newFragment, String tagFragmentNew, int framelayout) {

		try {
			FragmentTransaction ft = fm.beginTransaction();
			Fragment existFragment = fm.findFragmentByTag(tagFragmentNew);

			if (existFragment == null) {
				ft.replace(framelayout, newFragment, tagFragmentNew);
				ft.addToBackStack(tagFragmentNew);
			}
			else {
				ft.replace(framelayout, existFragment);
			}
			ft.commit();

		}
		catch (Exception exp) {

		}
	}

	public static void showHideInfo(AnimationRelativeLayout relativeLayout) {
		if (relativeLayout.getVisibility() == View.GONE || relativeLayout.getVisibility() == View.INVISIBLE) {
			relativeLayout.show(true, false);
		}
		else {
			relativeLayout.hide(true, true);
		}

	}

	public static Date getDate(int distanceInDate) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, distanceInDate);
		return cal.getTime();
	}

	public static Date getDateObjectFromStringDate(String strDate, String format) {
		Date date = new Date();
		try {
			SimpleDateFormat formater = new SimpleDateFormat(format, Locale.US);
			date = formater.parse(strDate);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}

	public static String getStringDateFromDateObject(Date date, String format) {
		String strDate = "";
		try {
			SimpleDateFormat formater = new SimpleDateFormat(format, Locale.US);
			strDate = formater.format(date);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return strDate;
	}

	public static String wrapperFormatDate(String strDate, String formatInput, String formatOutput) {
		String result = "";
		try {
			SimpleDateFormat formaterIn = new SimpleDateFormat(formatInput, Locale.US);
			SimpleDateFormat formaterOut = new SimpleDateFormat(formatOutput, Locale.US);
			result = getStringDateFromDateObject(getDateObjectFromStringDate(strDate, formatInput), formatOutput);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String getCurrentFragmentTag(FragmentActivity fragmentActivity, int framelayout) {

		return fragmentActivity.getSupportFragmentManager().findFragmentById(framelayout).getTag().toString();

	}

	public static void removeFragment(FragmentActivity fragmentActivity, String tag) {
		try {
			FragmentManager fm = fragmentActivity.getSupportFragmentManager();
			FragmentTransaction ft = fm.beginTransaction();
			ft.remove(fm.findFragmentByTag(tag)).commit();
		}
		catch (Exception exp) {
		}
	}

	public static String decodeBitmapToFile(Bitmap bm, Context me) {

		File file = null;
		try {

			file = new File(me.getCacheDir(), "crop");
			try {
				file.createNewFile();
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// Convert bitmap to byte array

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bm.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
			byte[] bitmapdata = bos.toByteArray();

			// write the bytes in file
			FileOutputStream fos = new FileOutputStream(file);
			try {
				fos.write(bitmapdata);
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (file.exists()) {
			return file.getAbsolutePath();
		}
		return "";
	}

	public static Bitmap setRotate(Bitmap bitmap, int angle) {
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
		Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(),
				scaledBitmap.getHeight(), matrix, true);
		return rotatedBitmap;
	}

	public static int getOrientation(String filePath) {
		int ori = 0;
		if (filePath != null) {
			ExifInterface exif = null;
			try {
				if (filePath.contains("file://"))
					exif = new ExifInterface(filePath.substring(7));
				else
					exif = new ExifInterface(filePath);

				int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
						ExifInterface.ORIENTATION_NORMAL);
				switch (exifOrientation) {
					case ExifInterface.ORIENTATION_UNDEFINED:

						break;
					case ExifInterface.ORIENTATION_NORMAL:

						break;
					case ExifInterface.ORIENTATION_ROTATE_180:
						ori = 180;

						break;
					case ExifInterface.ORIENTATION_ROTATE_90:
						ori = 90;

						break;
					case ExifInterface.ORIENTATION_ROTATE_270:
						ori = 270;

						break;
					default:

						break;
				}

			}
			catch (IOException e) {
				Log.e("getOrientation>", "getOrientation(String filePath) method: ", e);
			}
			return ori;
		}
		return ori;
	}
}